package com.hunantv.mglive.utils;

import android.os.Handler;
import android.os.Message;

import com.hunantv.mglive.data.ChatDataModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by qiudaaini@163.com on 16/2/5.
 */
public class MessageUtil {
    private static final int MAX_MSG_NUM = 150;
    private int mMaxTempNum = 5;
    private int mSpaceTime = 100;
    private iNotifyMsgListCallBack mCallback;
    private final List<ChatDataModel> mChatList;
    private final List<ChatDataModel> mChatListTemp = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            synchronized (mChatListTemp) {
                try {
                    mChatList.addAll(mChatListTemp);
                    if (mChatList.size() > MAX_MSG_NUM) {
                        int count = mChatList.size() - MAX_MSG_NUM;
                        for (int i = 0; i < count; i++) {
                            mChatList.remove(i);
                        }
                    }
                    if (mCallback != null) {
                        mCallback.notifyList();
                    }
                    mChatListTemp.clear();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };


    public MessageUtil(List<ChatDataModel> mChatList, iNotifyMsgListCallBack callBack) {
        this.mChatList = mChatList;
        this.mCallback = callBack;
    }

    /**
     * 用户切换输入状态时，调整聊天消息的过滤时间间隔
     *
     * @param change 是否输入
     */
    public void changeSpaceTime(boolean change) {
        if (change) {
            mSpaceTime = 1000;
            mMaxTempNum = 3;
        } else {
            mSpaceTime = 200;
            mMaxTempNum = 4;
        }
    }

    /**
     * 新增消息
     *
     * @param model 消息对象
     * @return 是否显示刷新，flase 表示抛弃 不用刷新
     */
    public synchronized void addMsg(ChatDataModel model) {
        synchronized (mChatListTemp) {
            if (mChatListTemp.size() < mMaxTempNum) {
                if (mChatListTemp.isEmpty()) {
                    mHandler.sendEmptyMessageDelayed(0, mSpaceTime);
                }
                mChatListTemp.add(model);
            } else {
                mChatListTemp.remove(0);
                mChatListTemp.add(model);
            }
        }
    }

    public interface iNotifyMsgListCallBack {

        void notifyList();
    }
}
